package com.jztd.servone.invoice.service;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单服务工厂类，用于获取不同类型的订单服务
 */
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class OrderServiceFactory {
    // 注入所有OrderService的实现类
    private final List<OrderService> orderServices;

    // 缓存服务实例的Map
    private static final Map<String, OrderService> serviceMap = new HashMap<>();

    /**
     * 初始化服务映射关系
     */
    public void init() {
        for (OrderService service : orderServices) {
            serviceMap.put(service.getServiceType(), service);
        }
    }

    /**
     * 根据服务类型获取对应的订单服务
     */
    public OrderService getOrderService(String serviceType) {
        // 如果Map为空，进行初始化
        if (serviceMap.isEmpty()) {
            init();
        }
        OrderService service = serviceMap.get(serviceType);
        if (service == null) {
            for (String ex : serviceMap.keySet()){
                System.out.println(ex);
            }
            throw new IllegalArgumentException("订单不存在");
        }
        return service;
    }
}
